#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import opengate as gate
import opengate.contrib.spect.ge_discovery_nm670 as spect_ge_nm670
from opengate.contrib.phantoms import nemaiec
from spect_helpers import add_177lu_sphere_sources
from pathlib import Path

if __name__ == "__main__":
    # create the simulation
    sim = gate.Simulation()

    # main options
    sim.g4_verbose = False
    # sim.visu = True
    sim.visu_type = "vrml"
    # sim.visu_type = "qt"
    sim.number_of_threads = 6
    sim.random_seed = "auto"
    sim.progress_bar = True
    sim.output_dir = "./output"

    # units
    m = gate.g4_units.m
    sec = gate.g4_units.second
    days = 3600 * 24 * sec
    cm = gate.g4_units.cm
    mm = gate.g4_units.mm
    nm = gate.g4_units.nm
    MeV = gate.g4_units.MeV
    keV = gate.g4_units.keV
    Bq = gate.g4_units.Bq
    kBq = 1000 * Bq
    MBq = 1000 * kBq
    cm3 = gate.g4_units.cm3
    Bq = gate.g4_units.Bq
    BqmL = Bq / cm3

    # world size
    sim.world.size = [2 * m, 2 * m, 2 * m]
    sim.world.material = "G4_AIR"

    # IEC phantom
    nemaiec.add_iec_phantom(sim, "iec")

    # spect head (debug mode = only a small part of the collimator is simulation, for visu mode)
    spect, colli, crystal = spect_ge_nm670.add_spect_head(sim, "spect")
    spect.translation = [0, 0, -28 * cm]

    # spect digitizer
    channels = [
        {"name": f"spectrum", "min": 3 * keV, "max": 515 * keV},
        {"name": f"scatter1", "min": 96 * keV, "max": 104 * keV},
        {"name": f"peak113", "min": 104.52 * keV, "max": 121.48 * keV},
        {"name": f"scatter2", "min": 122.48 * keV, "max": 133.12 * keV},
        {"name": f"scatter3", "min": 176.46 * keV, "max": 191.36 * keV},
        {"name": f"peak208", "min": 192.4 * keV, "max": 223.6 * keV},
        {"name": f"scatter4", "min": 224.64 * keV, "max": 243.3 * keV},
    ]
    # spect digitizer
    proj = spect_ge_nm670.add_digitizer(sim, "spect_crystal", channels)
    proj.output_filename = Path("output") / "projection3.mhd"

    # Lu177 source (only the gammas) in all spheres
    add_177lu_sphere_sources(sim, activity=1e4 * BqmL)

    # add stat actor
    stats = sim.add_actor("SimulationStatisticsActor", "stats")
    stats.track_types_flag = True
    stats.output_filename = Path("output") / "stats3.txt"

    # phys
    sim.physics_manager.physics_list_name = "G4EmStandardPhysics_option3"
    sim.physics_manager.set_production_cut("world", "all", 1 * mm)

    # ---------------------------------------------------------------------
    # start simulation
    # sim.running_verbose_level = gate.EVENT
    sim.run_timing_intervals = [[0, 100 * sec]]
    sim.run()

    # print stats
    print(stats)
